<?php

namespace app\controller;

use app\model\Download;
use app\model\TorrentBank;
use app\api\QbApi;
use app\api\TrApi;
use support\Request;

/**
 * 下载器配置的增删改查
 */
class DownloadsController
{
  // 设定无需鉴权的函数
  protected $noNeedLogin = [];


  public function index()
  {
    try {
      $download = new Download();
      $result = $download->select();
      return json(["code" => 200, "msg" => "获取成功", "data" => $result]);
    } catch (\Exception $e) {
      return json(["code" => 400, "msg" => "获取失败"]);
    }
  }

  /**
   * 添加下载器配置
   */
  public function add(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['name', 'type', 'host', 'port', 'username', 'password', 'save_path', 'is_skip_hash', 'is_paused', 'status', 'reseed_sites']);
      try {
        Download::create($data);
        return json(["code" => 200, "msg" => "下载器添加成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 更新下载器信息
   */
  public function update(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id', 'name', 'type', 'host', 'port', 'username', 'password', 'save_path', 'is_skip_hash', 'is_paused', 'status', 'reseed_sites']);
      try {
        Download::update($data);
        return json(["code" => 200, "msg" => "下载器修改成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }

  /**
   * 下载器删除
   */
  public function delete(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id']);
      try {
        Download::where('id', $data['id'])->delete();
        // 同时将种子库中的相关种子删除
        TorrentBank::where('download_id', $data['id'])->delete();
        return json(["code" => 200, "msg" => "下载器删除成功"]);
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);
  }
  /**
   * 下载器连接性测试
   * @auth true
   */
  public function connectCheck(Request $request)
  {
    if ($request->method() == "POST") {
      $data = $request->only(['id']);
      try {
        $id = $data['id'];
        $downloadData = Download::where('id', $id)->findOrEmpty();
        if ($downloadData['type'] == 1) {
          $api = new Qbapi($downloadData);
        } else {
          $api = new Trapi($downloadData);
        }
        if ($api->login_status) {
          return json(["code" => 200, "msg" => "登录成功"]);
        } else {
          return json(["code" => 200, "msg" => "登录失败"]);
        }
      } catch (\Exception $e) {
        return json(["code" => 400, "msg" => $e->getMessage()]);
      }
    }
    return json(["code" => 400, "msg" => "请用POST请求"]);

  }
}
